package handler

import (
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"webTools/model"
	"webTools/util"
)

type htmlInfo struct {
	H1 string `json:"h1"`
}

// GetHtmlInfoHandler 获取网页信息
func GetHtmlInfoHandler(c *gin.Context) {
	url := c.Query("url")
	log.Println("url: ", url)
	htmInfo, err := getHtmlInfo(url)
	var result *model.Result
	if err != nil {
		result = model.Error(1, err.Error())
	} else {
		log.Println(htmInfo)
		result = model.Success(htmInfo)
	}
	c.JSON(http.StatusOK, result)
}

// getHtmlInfo 获取网页信息
func getHtmlInfo(url string) (*htmlInfo, error) {
	h1Text, err := getSelectorText(url, "h1")
	if err != nil {
		return nil, err
	}
	return &htmlInfo{H1: h1Text}, nil
}

// getSelectorText 获取网络标签中文字内容
func getSelectorText(url string, selector string) (string, error) {
	res, err := http.Get(url)
	if err != nil {
		return "", fmt.Errorf("url请求失败")
	}
	document, err := goquery.NewDocumentFromReader(res.Body)
	if err != nil {
		return "", fmt.Errorf("获取网页标题失败")
	}
	appName, err := util.DecodeToGBK(document.Find(selector).Text())
	if err != nil {
		return "", fmt.Errorf("网页标题GBK转utf-8失败")
	}
	return appName, nil
}
